package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询行为实体
     *
     * @param userId      用户id
     * @param equipmentId 设备id
     * @return
     */
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        if (userId == null && equipmentId == null) {
            return null;
        }
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        if (userId != null) {
            Query refId = Query.query(Criteria.where("refId").is(userId));

          ApBehaviorEntry   apBehaviorEntry1 = mongoTemplate.findOne(refId, ApBehaviorEntry.class);
            if (apBehaviorEntry1 == null) {
                apBehaviorEntry.setType((short) 1);
                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }else {
                return apBehaviorEntry1;
            }

        }

        if (userId == null && equipmentId != null) {
            Query refId = Query.query(Criteria.where("refId").is(equipmentId));

         ApBehaviorEntry   apBehaviorEntry2 = mongoTemplate.findOne(refId, ApBehaviorEntry.class);
            if (apBehaviorEntry2 == null) {
                apBehaviorEntry.setType((short) 0);
                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }else {
                return apBehaviorEntry2;
            }

        }

        return apBehaviorEntry;

    }
}
